﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Hospital.Models;

namespace Hospital.Controllers
{
    public class DocController : Controller
    {
        private DataManager _dataManager;

        public DocController(DataManager dataManager)
        {
            _dataManager = dataManager;
        }

        [Authorize(Roles = "Admin")]
        public ActionResult List()
        {
            ViewData["Title"] = "Список специалистов";
            ViewData["Doc"] = _dataManager.doc.GetDoctors();
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Doc(int id)
        {
            ViewData.Model = _dataManager.doc.GetDoctor(id);
            return View();
        }

        [Authorize(Roles = "Admin")]
        public ActionResult Delete(int id)
        {
            _dataManager.doc.DeleteDoc(id);
            return RedirectToAction("List");
        }

        [Authorize(Roles = "Admin")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Edit(int id)
        {
            Doctor m = _dataManager.doc.GetDoctor(id);
            ViewData.Model = m;

            SetEditList(m);
            return View();                        
        }

        private void SetEditList(Doctor m)
        {
            ViewData["Users"] = new SelectList(_dataManager.Membership.GetUsers(), "ProviderUserKey", "UserName", m.AssignedOn);
        
        }

        [Authorize(Roles = "Admin")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, Doctor m)
        {
            if (m.FIO == null) ModelState.AddModelError("FIO", "Поле не может быть пустым");
            else
                if (m.FIO.Length < 5) ModelState.AddModelError("FIO", "ФИО не может быть короче 5 символов");
            
            if (ModelState.IsValid)
            {
                m.Id_Doc = id;
                _dataManager.doc.UpdateDoctor(m);
                return RedirectToAction("List");
            }
            SetEditList(m);
            return View();
        }

        [Authorize(Roles = "Admin")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Add()
        {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add(string fio, string spec, string uchastok, string kab)
        {
            if (fio == null) ModelState.AddModelError("FIO", "Поле не может быть пустым");
            else
                if (fio.Length < 5) ModelState.AddModelError("FIO", "ФИО не может быть короче 5 символов");

            if (ModelState.IsValid)
            {
                _dataManager.doc.AddDoctor(fio, spec, uchastok, kab);
                return RedirectToAction("List");
            }
            return View();
        }

    }
}
